package com.base.voicerecorod.view;

import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;

import com.base.voicerecorod.AudioManager;
import com.base.voicerecorod.DialogMannager;
import com.base.voicerecorod.R;

/**
 * Created by aman on 16/4/14.
 */
public class AudioRecordButton extends Button implements AudioManager.AudioStateListener{

    private static final int DISTANCE_Y_CANCEL = 50;
    private static final int STATE_NORMAL = 1;
    private static final int STATE_RECORDING = 2;
    private static final int STATE_WANT_TO_CANCLE = 3;

    private int mCurState = STATE_NORMAL;
    private boolean isRecording = false; //是否开始录音了

    private DialogMannager mDialogManager;
    private AudioManager mAudioManager;

    private float mTime;
    //是否触发longclick
    private boolean mReady;

    public AudioRecordButton(Context context) {
        this(context, null);
    }

    public AudioRecordButton(Context context, AttributeSet attrs) {
        super(context, attrs);

        mDialogManager = new DialogMannager(getContext());

        String dir = Environment.getExternalStorageDirectory() + "/imooc_recorder_audios";

        mAudioManager = AudioManager.getInstance(dir);
        mAudioManager.setAudioStateListener(this);

        setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                mReady = true;
                mAudioManager.prepareAudio();
                return false;
            }
        });
    }

    public interface AudioFinishRecordListener{
        void onFinish(Float seconds, String filePath);
    }

    private AudioFinishRecordListener mListener;

    public void setAudioFinishRecorderListener(AudioFinishRecordListener listener) {
        this.mListener = listener;
    }

    /**
     *
     */
    private Runnable mGetVoiceLevelRunnable = new Runnable() {
        @Override
        public void run() {
                  while (isRecording) {
                      try {
                          Thread.sleep(100);
                          mTime += 0.1f;
                          mHandler.sendEmptyMessage(MSG_VOICE_CHANGED);
                      } catch (InterruptedException e) {
                          e.printStackTrace();
                      }
                  }
        }
    };


    private static  final int MSG_AUDIO_PREPARED = 0X110;
    private static  final int MSG_VOICE_CHANGED = 0X111;
    private static  final int MSG_DIALOG_DIMISS = 0X112;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case MSG_AUDIO_PREPARED:
                    // 真正显示应该在audio end prepared以后
                    mDialogManager.showRecordDialog();
                    isRecording = true;
                    new Thread(mGetVoiceLevelRunnable).start();
                    break;
                case MSG_VOICE_CHANGED:
                    mDialogManager.updateVoiceLevel(mAudioManager.getVoiceLevel(7));
                    break;
                case MSG_DIALOG_DIMISS:
                    mDialogManager.dimissDialog();
                    break;
            }
        }
    };


    @Override
    public void wellPrepared() {
        mHandler.sendEmptyMessage(MSG_AUDIO_PREPARED);
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {

        int action = event.getAction();
        int x = (int) event.getX();
        int y = (int) event.getY();

        switch (action) {
            case MotionEvent.ACTION_DOWN:
                isRecording = true;
                changeState(STATE_NORMAL);
                break;
            case MotionEvent.ACTION_MOVE:
                if (isRecording) {
                    //是否想要取消
                    if (wantToCancel(x, y)) {
                        changeState(STATE_WANT_TO_CANCLE);
                    } else {
                        changeState(STATE_RECORDING);
                    }
                }


                break;
            case MotionEvent.ACTION_UP:
                if (!mReady) {
                    reset();
                    return super.onTouchEvent(event);
                }

                if (!isRecording || mTime < 0.6) {
                    mDialogManager.tooShort();
                    mAudioManager.cancel();
                    mHandler.sendEmptyMessageDelayed(MSG_DIALOG_DIMISS, 1300);
                } else if (mCurState == STATE_RECORDING) { //正常录制结束
                    //release
                    mDialogManager.dimissDialog();
                    mAudioManager.release();
                    //callbackToAct
                    if (mListener!= null) {
                        mListener.onFinish(mTime, mAudioManager.getCurrentFilePath());
                    }
                } else if(mCurState == STATE_WANT_TO_CANCLE){
                    //cancel
                    mDialogManager.dimissDialog();
                    mAudioManager.cancel();
            }
                reset();
                break;
        }

        return super.onTouchEvent(event);
    }


    /**
     * 恢复状态及标志位
     */
    private void reset() {
        mTime = 0;
        mReady = false;
        isRecording = false;
        changeState(STATE_NORMAL);
    }

    /**
     * 想要取消
     * @param x
     * @param y
     * @return
     */
    private boolean wantToCancel(int x, int y) {

        if (x < 0 || x > getWidth()) {
            return true;
        }
        if (y< -DISTANCE_Y_CANCEL || y > getHeight() + DISTANCE_Y_CANCEL) {
            return true;
        }
        return false;
    }

    /**
     * 改变状态
     * @param state
     */
    private void changeState(int state) {

        if (mCurState != state) {
            mCurState = state;
            switch (state) {
                case STATE_NORMAL:
                    setBackgroundResource(R.drawable.btn_recorder_normal);
                    setText(R.string.str_recorder_normal);
                    break;
                case STATE_RECORDING:
                    setBackgroundResource(R.drawable.btn_recordering);
                    setText(R.string.str_recorder_recording);
                    if (isRecording) {
                        mDialogManager.recording();
                    }
                    break;
                case STATE_WANT_TO_CANCLE:
                    setBackgroundResource(R.drawable.btn_recordering);
                    setText(R.string.str_recorder_want_cancel);
                    mDialogManager.wantToCancel();
                    break;
            }
        }

    }

}
